import { message } from 'ant-design-vue'
import { useStore } from '@/store'
import { localStorage } from '@/utils'
const AXIOS_TIMEOUT = 100000

const BASE_URL ="http//......"


/**
 * 请求方法
 */
export const METHOD = {
  GET: 'get',
  POST: 'post',
  DELETE: 'delete',
  PUT: 'put'
}

/**
 * 显示消息提示
 * 
 * @param {*} msg 
 * @param {*} options 
 * @returns 
 */
const showMessage = (msg, options = {}) => {
  if (!msg) return

  // 先解析config中_msgConfig配置信息
  const msgConfig = options?._msgConfig || {}

  message.error(Object.assign({}, msgConfig, {
    content: msg
  }))
}

/**
 * 响应信息处理
 */
const handleResponse = (response, options) => {
  const { url, _data, status } = response

  const { spin } = useStore()
  spin.close()

  // 检查当前http状态
  if (status != 200) {
    // 说明为异常状态，根据状态码进行消息提示
    if (status == 401 || status == 403) {
      const erMsg = '请求未授权'
       showMessage(erMsg, options)
       return Promise.reject(erMsg)
    }
    if (status == 405) {
      const erMsg = '不允许跨域处理'
      showMessage(erMsg, options)
      return Promise.reject(erMsg)
    }
    if (status == 500 || status == 502 || status == 503 || status == 504) {
      const erMsg = '服务器异常，请稍后重试'
      showMessage(erMsg, options)
      return Promise.reject(erMsg)
    }
    const erMsg = '请求无效'
    showMessage(erMsg, options)
    return Promise.reject(erMsg)
  }

  /**
   * 成功消息
   */
  if (_data.code === '200') {
    return Promise.resolve(_data)
  }


  // 强制跳转登录授权
  if (_data.code === '401') {
    return Promise.reject(_data)
  }

  
  return Promise.reject(_data)
}

/**
 * get方法传递数组形式参数
 * 
 * @param {*} params 
 * @returns 
 */
const paramsSerializer = (params) => {
  if (!params) return
  const query = params
  Object.entries(query).forEach(([key, val]) => {
    if (typeof val === 'object' && Array.isArray(val) && val !== null) {
      query[`${key}[]`] = toRaw(val).map((v) => JSON.stringify(v))
      delete query[key]
    }
  })
  return query
}

/**
 * 单独创建请求服务
 */
export const fetch = $fetch.create({
  // 请求拦截器
  onRequest({ options }) {
    // get方法传递数组形式参数
    options.params = paramsSerializer(options.params)
    
    // 后端请求地址
    options.baseURL = BASE_URL


    // 转化header信息
    options.headers = new Headers(options.headers)
    options.headers.set('Nb-Device-Id', localStorage.get('deviceId', ''))

    // 添加请求头,没登录不携带token
    const { user } = useStore()
    if (!options.headers.get('Authorization') && user.getToken) {
      options.headers.set('Authorization', user.getToken)
    }
  },
  // 响应拦截
  onResponse({ response, options }) {
    return handleResponse(response, options)
  },
  // 错误处理
  onResponseError({ response }) {
    const { spin } = useStore()
    spin.close()
    return Promise.reject(response._data)
  }
})

// 自动导出
export const useHttp = {
  get: (url, data, { timeout = AXIOS_TIMEOUT, headers = {}, ...options } = {}) => {
    return fetch(url, {
      method: METHOD.GET,
      params: data ? data : '',
      timeout: timeout ? timeout : AXIOS_TIMEOUT,
      headers: headers,
      ...options
    })
  },
  post: (url, data, { timeout = AXIOS_TIMEOUT, headers = {}, ...options } = {}) => {
    return fetch(url, {
      method: METHOD.POST,
      body: data ? data : '',
      timeout: timeout ? timeout : AXIOS_TIMEOUT,
      headers: headers,
      ...options
    })
  },
  put: (url, data, { timeout = AXIOS_TIMEOUT, headers = {}, ...options } = {}) => {
    return fetch(url, {
      method: METHOD.PUT,
      body: data ? data : '',
      timeout: timeout ? timeout : AXIOS_TIMEOUT,
      headers: headers,
      ...options
    })
  },
  delete: (url, data, { timeout = AXIOS_TIMEOUT, headers = {}, ...options } = {}) => {
    return fetch(url, {
      method: METHOD.DELETE,
      body: data ? data : '',
      timeout: timeout ? timeout : AXIOS_TIMEOUT,
      headers: headers,
      ...options
    })
  }
}
